Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

Follow up:

Did you use extra space?

A straight forward solution using O(mn) space is probably a bad idea.

A simple improvement uses O(m + n) space, but still not the best solution.

Could you devise a constant space solution?

Solution:

  1. public class Solution {
  2. public void setZeroes(int[][] matrix) {
  3. int n = matrix.length;
  4. int m = matrix[0].length;
  5. // Check if we need to set zeros for first row and column
  6. boolean cleanFirstRow = false;
  7. boolean cleanFirstCol = false;
  8. for (int j = 0; j < m; j++) {
  9. if (matrix[0][j] == 0) {
  10. cleanFirstRow = true;
  11. break;
  12. }
  13. }
  14. for (int i = 0; i < n; i++) {
  15. if (matrix[i][0] == 0) {
  16. cleanFirstCol = true;
  17. break;
  18. }
  19. }
  20. // Use first row and first column to save the flags
  21. for (int i = 1; i < n; i++) {
  22. for (int j = 1; j < m; j++) {
  23. if (matrix[i][j] == 0) {
  24. matrix[0][j] = 0;
  25. matrix[i][0] = 0;
  26. }
  27. }
  28. }
  29. // Based on the flags set other cells
  30. for (int i = 1; i < n; i++) {
  31. for (int j = 1; j < m; j++) {
  32. if (matrix[0][j] == 0 || matrix[i][0] == 0) {
  33. matrix[i][j] = 0;
  34. }
  35. }
  36. }
  37. // At last set the first row and column
  38. if (cleanFirstRow) {
  39. for (int j = 0; j < m; j++) {
  40. matrix[0][j] = 0;
  41. }
  42. }
  43. if (cleanFirstCol) {
  44. for (int i = 0; i < n; i++) {
  45. matrix[i][0] = 0;
  46. }
  47. }
  48. }
  49. }